<template>
    <div class="main_container">
        <div v-if="pageName=='index'">
            <el-form :model="queryParams" label-width="auto">
                <el-row>
                    <el-col :span="7">
                        <el-form-item label="关键词:">
                            <el-input style="width: 240px;" maxlength="50" v-model="queryParams.search" placeholder="供货商名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="供货商分类:">
                            <el-select style="width: 240px;" v-model="queryParams.category" placeholder="请选择" clearable>
                                <el-option v-for="item in cateLists" :key="'cate_'+item.id" 
                                    :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-button size="small" icon="el-icon-search" @click="handleQuery"
                            style="margin: 8px 0 0 20px;" class="btn_primary_color">查询</el-button>
                    </el-col>
                </el-row>
            </el-form>
            <el-row :gutter="16" class="mb8">
                <el-col :span="1.5">
                    <el-button
                    class="btn_primary_color"
                    icon="el-icon-plus"
                    size="small"
                    @click="handleAdd"
                    v-hasPermi="['supplier_add']"
                    >新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                    class="btn_primary_color"
                    icon="el-icon-download"
                    size="small"
                    @click="handleImport"
                    v-hasPermi="['supplier_import']"
                    >导入</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                    :class="multiple?'btn_info_color':'btn_primary_color'"
                    size="small"
                    icon="el-icon-upload2"
                    @click="handleExport"
                    :loading='exportLoading'
                    :disabled="multiple"
                    v-hasPermi="['supplier_export']"
                    >导出所选</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                    class="btn_primary_color"
                    size="small"
                    icon="el-icon-upload2"
                    @click="handleExport('all')"
                    :loading='exportLoading'
                    v-hasPermi="['supplier_export']"
                    >导出全部</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                    :class="multiple?'btn_info_color':'btn_remove_color'"
                    size="small"
                    icon="el-icon-delete"
                    @click="handleRemoveSelect"
                    :loading='exportLoading'
                    :disabled="multiple"
                    v-hasPermi="['supplier_del']"
                    >删除所选</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                    class="btn_primary_color"
                    icon="el-icon-setting"
                    size="small"
                    @click="handleSetting"
                    >设置供货商分类</el-button>
                </el-col>
            </el-row>
            <el-table border :data="supplierList" style="margin-top: 15px;" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="名称" align="left" prop="name" />
                <el-table-column label="简称" align="left" prop="abbr_name" />
                <el-table-column label="分类" align="left" prop="cateName" />
                <el-table-column label="联系人" align="left" prop="contact" />
                <el-table-column label="联系电话" align="left" prop="phone" />
                <el-table-column label="期初欠款" align="left" prop="initial_money" />
                <el-table-column label="应付款" align="left" prop="current_money" />
                <el-table-column label="邮箱" align="left" prop="email" />
                <el-table-column label="微信" align="left" prop="wechat" />
                <el-table-column label="地址" align="left" prop="addr" />
                <el-table-column label="操作" min-width="140" align="left" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleView(scope.row)"
                            style="font-weight: bold;"
                        >查看</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleEdit(scope.row)"
                            style="font-weight: bold;"
                            v-hasPermi="['supplier_update']"
                        >编辑</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            @click="handlePay(scope.row)"
                            style="font-weight: bold;"
                            v-hasPermi="['supplier_payment_add']"
                        >付款</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleRemove(scope.row)"
                            style="font-weight: bold;"
                            v-hasPermi="['supplier_del']"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-show="total>0"
                background
                style="padding: 32px 16px;background: #fff;text-align: right;"
                @size-change="getSuppliers"
                @current-change="getSuppliers"
                :current-page.sync="pageParam.page"
                :page-size="pageParam.num"
                layout="total, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <!-- 新增页面 -->
        <common-dialog :visiable="pageName == 'add'">
            <add :corpId="corp_id" @success="success" @hidden="hidden"></add>
        </common-dialog>

        <!-- 编辑页面 -->
        <common-dialog :visiable="pageName == 'edit'">
            <add :corpId="corp_id" :editId="editId" @success="success" @hidden="hidden"></add>
        </common-dialog>

        <!-- 查看 -->
        <el-dialog destroy-on-close :visible.sync="showSupplierInfo" title="查看供货商信息" append-to-body>
            <el-row>
                <el-form ref="viewForm" :model="viewForm" size="small" label-width="auto">
                    <el-col :span="12">
                        <el-form-item label="名称：">
                            <div>{{ viewForm.name }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="简称：">
                            <div>{{ viewForm.abbr_name }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分类：">
                            <div>{{ viewForm.cateName }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人：">
                            <div>{{ viewForm.contact }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话：">
                            <div>{{ viewForm.phone }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱：">
                            <div>{{ viewForm.email }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="微信：">
                            <div>{{ viewForm.wechat }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="地址：">
                            <div>{{ viewForm.addr }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="期初欠款：">
                            <div>{{ viewForm.initial_money }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="应付款：">
                            <div>{{ viewForm.current_money }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注：">
                            <div>{{ viewForm.remark }}</div>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div slot="footer">
                <el-button @click="showSupplierInfo=false">关闭</el-button>
            </div>
        </el-dialog>

        <el-drawer
            title="设置供货商分类"
            append-to-body
            :visible.sync="showsupplierSet"
            :wrapperClosable="false"
            :before-close="handleClose">
            <div class="cates_view">
                <el-button class="btn_primary_color" icon="el-icon-plus" size="small" @click="handleAddCategory">新增分类</el-button>
                <div class="lists">
                    <div class="item" v-for="item in cateLists" :key="'cate'+item.id">
                        <div class="name">{{ item.name }}</div>
                        <div class="btns">
                            <el-button
                                size="mini"
                                type="text"
                                @click="handleEditCategory(item)"
                                style="font-weight: bold;"
                            >编辑</el-button>
                            <el-button
                                size="mini"
                                type="text"
                                @click="handleRemoveCategory(item)"
                                style="font-weight: bold;"
                            >删除</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </el-drawer>
        
        <el-dialog
            :title="cateEditDialogTitle"
            :visible.sync="showCategoryAdd"
            width="30%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-form :model="cateInfo" label-width="auto" ref="cateForm" :rules="rules">
                    <el-form-item label="分类名称:" prop="name">
                        <el-input style="width: 240px;" maxlength="100" v-model="cateInfo.name" placeholder="请输入" clearable />
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showCategoryAdd=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addSupplierCategory">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 导入弹窗 -->
        <el-dialog
            title="导入销售单"
            :visible.sync="showImport"
            width="40%"
            append-to-body
            @close="closeImport"
            :close-on-click-modal="false"
            center>
            <div class="upload_view">
                <el-upload drag
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-remove="handleRemoveFile"
                    :http-request="(params) => uploadSectionFile(params, 'picUpload')" 
                    :accept="picUpload.accept.join(',')"
                    :file-list="fileList"
                    action="anything">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">
                        <div style="display: flex;align-items: center;justify-content: space-between;">
                            <span>只能上传{{ picUpload.accept.join('、') }}文件，且不超过{{ picUpload.max }}MB</span>
                            <span style="color: #068CEE;cursor: pointer;" @click="downloadTemplate">下载模板</span>
                        </div> 
                        <div v-if="showImportError" style="display: flex;align-items: center;justify-content: space-between;color: red;margin-top: 10px;">
                            <span class="shake_words">{{ taskInfo.error_msg }}</span>
                            <span style="color: #068CEE;cursor: pointer;" @click="downloadFail">下载导入失败文件</span>
                        </div>
                    </div>
                </el-upload>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button class="btn_primary_color" @click="startUpload">开始导入</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import commonDialog from "@/components/commonDialog";
import { commonUpload } from '@/api/util';
import { baseUrl } from '@/config/env';
import { addDownloadTask, addImportTask, getImportTaskInfo } from '@/api/common';
import { getSupplierList, getSupplierCates, addSupplierCate, removeBatchSupplier,
    editSupplierCate, removeSupplierCate, removeSupplier } from "@/api/cooperate";
const moment = require('moment')

export default {
    name: 'supplierList',
    data() {
        return {
            fullPageLoading: null,  //全屏loading
            showImportError: false,
            showImport: false,
            picUpload: {
                max: 10,
                accept: ['.xls', '.xlsx']
            },
            fileList: [],
            uploadParam: {},
            taskInfo: {},
            timer: null,
            exportParam: {
                corp_id: '',
                params: {},
                task_type: 'export_supplier',
                params_method: 0,
                file_name: '供货商'+moment().format('yyyyMMDDHHmmss')+'.xlsx'
            },
            multiple: true, // 非多个禁用
            exportLoading: false,
            showsupplierSet: false,
            showCategoryAdd: false,
            showSupplierInfo: false,
            corp_id: '',
            editId: '',
            pageName: 'index',
            queryParams: {
                search: '',
                category: '',
                ordering: '-update_datetime,-id'
            },
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            supplierList: [],
            cateLists: [],
            cateEditDialogTitle: '',
            cateInfo: {
                name: ''
            },
            rules:{
                name: [
                    { required: true, message: "请输入分类名称", trigger: "blur" },
                ],
            },
            viewForm: {},
            selectIds: []
        }
    },
    components: {
        commonDialog,
        add: () => import('./edit.vue'),
    },
    created() {
        this.corp_id = this.$store.state.corpId
        this.exportParam.corp_id = this.corp_id
        this.getCategorys()
        this.getSuppliers()
        if (this.$route.query.from){
            this.pageName = 'add'
        }
    },
    methods: {
        // 按条件筛选
        handleQuery() {
            this.pageParam.page = 1
            this.getCategorys()
            this.getSuppliers()
        },
        // 获取供货商分类
        getCategorys() {
            getSupplierCates({
                corp: this.corp_id,
                page: 1,
                num: 999
            }).then(res => {
                this.cateLists = res.data.data.category_list
            })
        },
        // 获取供货商列表
        getSuppliers() {
            this.queryParams.corp = this.corp_id
            let params = Object.assign({}, this.queryParams, this.pageParam)
            getSupplierList(params).then(res => {
                this.supplierList = res.data.data.supplier_list.filter(item => {
                    if (item.category_detail && item.category_detail.name) {
                        item.cateName = item.category_detail.name
                    }else{
                        item.cateName = ''
                    }
                    item.initial_money = '￥'+item.initial_money
                    item.current_money = '￥'+item.current_money
                    return item
                })
                this.total = res.data.data.total
            })
        },
        hidden(res) {
            console.log(res)
            if (res && res.isRefresh){
                this.getCategorys()
            }
            this.pageName = 'index'
        },
        success() {
            this.pageName = 'index'
            this.handleQuery()
        },
        // 新增
        handleAdd() {
            this.editId = null
            this.pageName = 'add'
        },
        // 查看
        handleView(item) {
            this.viewForm = item
            this.showSupplierInfo = true
        },
        // 编辑
        handleEdit(item) {
            this.editId = item.id
            this.pageName = 'edit'
        },
        handlePay(item) {
            this.$router.push({
                path: 'payOrder',
                query: {
                    supId: item.id,
                    supName: encodeURIComponent(item.name)
                }
            })
        },
        // 删除所选
        handleRemoveSelect() {
            let that = this
            this.$confirm('您确定要删除选中的供货商吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeBatchSupplier({
                    corp_id: that.corp_id,
                    pk_id_list: that.selectIds
                }).then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        // 删除
        handleRemove(item) {
            let that = this
            this.$confirm('您确定要删除该供货商吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeSupplier(item.id, {
                    corp: that.corp_id
                }).then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        // 导入
        handleImport() {
            this.showImportError = false
            this.showImport = true
        },
        closeImport() {
            this.uploadParam = {}
            this.fileList = []
            this.showImport = false
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            // console.log(selection);
            this.multiple = !selection.length
            let ids = selection.map(item => item.id)
            this.selectIds = ids
            if (ids.length){
                this.exportParam.params.id_list = ids.join(',');
            }
        },
        // 导出
        handleExport(type) {
            this.exportParam.params = Object.assign({}, this.exportParam.params, this.queryParams)
            if (type && type=='all'){
                delete this.exportParam.params['id_list']
            }
            addDownloadTask(this.exportParam).then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: '文件正在下载中，请至任务列表中查看',
                        type: 'success',
                        duration: 2000
                    })
                    this.$store.dispatch('GetTaskList', this.corp_id); 
                    this.$store.dispatch('startInterval')
                }
            })
        },
        // 设置供货商分类
        handleSetting() {
            this.showsupplierSet = true
        },
        // 新增分类
        handleAddCategory() {
            this.cateInfo.name = ''
            this.cateEditDialogTitle = '新增供货商分类'
            this.showCategoryAdd = true
        },
        addSupplierCategory() {
            var that = this
            that.$refs['cateForm'].validate(valid => {
                if(!valid) return

                let temp = null
                if (that.cateInfo.id) {
                    temp = editSupplierCate(that.cateInfo.id,{
                        corp: that.corp_id,name: that.cateInfo.name
                    })
                }else{
                    temp = addSupplierCate({corp: that.corp_id,name: that.cateInfo.name})
                }
                temp.then(res => {
                    if (res.code == 200){
                        that.cateInfo.name = ''
                        that.cateInfo.id = ''
                        that.getCategorys()
                        that.showCategoryAdd = false
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                    }
                })
            })
        },
        // 编辑分类
        handleEditCategory(item) {
            this.cateInfo.name = item.name
            this.cateInfo.id = item.id
            this.cateEditDialogTitle = '编辑供货商分类'
            this.showCategoryAdd = true
        },
        // 删除分类
        handleRemoveCategory(item) {
            let that = this
            this.$confirm('您确定要删除该供货商分类吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeSupplierCate(item.id, {
                    corp: that.corp_id
                }).then(res => {
                    if (res.code == 200){
                        that.getCategorys()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        handleClose(done){
            done();
        },
        
        //  ------------------------------- 文件上传相关 --------------------------------
        // 文件超出个数限制时
        handleExceed() {
            this.$message.warning('只能上传一个文件，若需要重新上传，请先删除已上传文件')
        },
        // 文件列表移除文件
        handleRemoveFile() {
            this.uploadParam = {}
        },
        // 上传前校验
        beforeUpload (file, uploadType) {
            let isRightSize = file.size / 1024 / 1024 < this[uploadType].max
            if (!isRightSize) {
                this.$message.error('文件大小超过' + this[uploadType].max + 'MB')
            }
            let fileArr = file.name.split('.')
            let ext = fileArr[fileArr.length - 1]
            let isAccept = new RegExp(this[uploadType].accept.join('|')).test('.' + ext.toLowerCase())
            if (!isAccept) {
                this.$message.error('请上传' + this[uploadType].accept.join(',') + '类型的文件')
            }
            return isRightSize && isAccept
        },
        // 附件上传
        uploadSectionFile (params, uploadType) {
            let _this = this
            if (!this.beforeUpload(params.file, uploadType)) {
                params.onError()
                return
            }
            
            let param = {
                corp: _this.corp_id,
                user: _this.$store.state.userInfo.id,
                file_path: params.file
            }
            commonUpload('/commons/inner_upload_file_view', param).then(res => {
                if (res.code == 200){
                    _this.$message.success('上传成功')
                    _this.uploadParam = res.data
                }else{
                    _this.$message.error('上传失败，请重新上传')
                    _this.uploadParam = {}
                } 
            })
        },
        // 开始上传
        startUpload() {
            if (Object.keys(this.uploadParam).length === 0){
                this.$message.error('请先上传要导入的文件')
                return
            }

            let that = this
            addImportTask({
                corp_id: this.uploadParam.corp,
                file_upload_id: this.uploadParam.id,
                task_type: 'import_supplier',
                file_name: ''
            }).then(res => {
                if (res.code == 200){
                    that.fullPageLoading = that.$loading({
                        lock: true,
                        text: '正在导入数据，请稍候...',
                        spinner: 'el-icon-loading',
                        // background: 'rgba(0, 0, 0, 0.7)'
                    });
                    that.timer = setInterval(() => {
                        that.getTaskStatus(res.data.id)
                    }, 5000);
                }
            })
        },
        // 获取导入任务详情
        getTaskStatus(pk_id) {
            let corp = this.corp_id
            getImportTaskInfo({corp, pk_id}).then(res => {
                let task_status = res.data.task_status
                if (task_status == 1){  //导入成功
                    clearInterval(this.timer)
                    this.fullPageLoading.close()
                    this.showImport = false
                    this.$message.success('导入成功')
                    this.handleQuery()
                }else if (task_status==2 || task_status==4){  //导入失败
                    clearInterval(this.timer)
                    this.fullPageLoading.close()
                    this.showImportError = true
                    this.taskInfo = res.data
                    this.taskInfo.error_msg = res.data.error_msg? ('导入失败：'+res.data.error_msg) : '导入失败'
                    this.handleQuery()
                }
            })
        },
        // 下载导入失败文件
        downloadFail() {
            let url = baseUrl+'/commons/download_import_error_file_view?pk_id='+this.taskInfo.id+'&token='+this.taskInfo.token+
				'&execute_time_unix='+this.taskInfo.execute_time_unix
                let that = this
				fetch(url).then(response => {
						if (!response.ok) {
							throw new Error('Network response was not ok');
						}
						return response.blob(); // 将响应转换为 Blob 对象
					})
					.then(blob => {
						const url = window.URL.createObjectURL(blob); // 创建一个指向 Blob 的 URL
						const a = document.createElement('a'); // 创建一个 <a> 元素
						a.style.display = 'none';
						a.href = url;
						a.download = '导入失败文件.xlsx'; // 设置下载的文件名
						document.body.appendChild(a);
						a.click(); // 模拟点击下载
						window.URL.revokeObjectURL(url); // 释放 Blob URL
						document.body.removeChild(a); // 移除 <a> 元素
						that.showPop = true
					})
					.catch(error => console.error('下载文件时出错:', error));
        },
        // 模板下载
        downloadTemplate() {
            window.location.href = 'https://anhuiyaoying.com/webs/template/%E4%BE%9B%E8%B4%A7%E5%95%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx'
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .cates_view {
        padding: 0 30px;
        .lists {
            margin-top: 15px;
            .item {
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 40px;
                border-top: 1px solid #eee;
                margin-bottom: 10px;
                .name {
                    font-size: 14px;
                    color: #333;
                }
            } 
        }
    }
    .upload_view {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
</style>
<style>
.el-drawer__header {
    font-weight: bold;
    color: #333;
    font-size: 15px;
}
.el-loading-spinner {
    top: 42% !important;
    color: #068CEE !important;
}
.el-loading-spinner .el-icon-loading {
    font-size: 34px !important;
    margin-bottom: 15px !important;
}
.el-loading-spinner .el-loading-text {
    font-size: 16px !important;
}
</style>